#define _CRT_SECURE_NO_WARNINGS
#include "head.h"

ListNode* Creatspace(DataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		printf ("malloc fail");
		exit(-1);
	}

	newnode->data = x;
	newnode->prev = NULL;
	newnode->next = NULL;

	return newnode;
}


// 创建返回链表的头结点.

ListNode* ListCreate()
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		printf("malloc fail");
		exit(-1);
	}

	newnode->prev = newnode;
	newnode->next = newnode;
	return newnode;
}


// 双向链表销毁

void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	ListNode* next = NULL;

	while (cur != pHead)
	{
		next = cur->next;
		free(cur);
		cur = next;
	}
	free(pHead);

}


// 双向链表打印

void ListPrint(ListNode* phead)
{
	ListNode* cur = phead->next;

	printf("head<=>");


	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}

	printf("NULL\n");
}


// 双向链表尾插

void ListPushBack(ListNode* phead, DataType x)
{
	
	assert(phead);

	ListNode* newnode = Creatspace(x);

	ListNode* prev = phead->prev;

	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = phead;
	phead->prev = newnode;

}


// 双向链表尾删

void ListPopBack(ListNode* phead)
{
	assert(phead);

	ListNode* cur  = phead->prev;
	ListNode* prev = cur->prev;

	free(cur);
	cur = NULL;

	prev->next = phead;
	phead->prev = prev;


}

// 双向链表头插

void ListPushFront(ListNode* phead, DataType x)
{
	assert(phead);

	ListNode* newnode = Creatspace(x);

	newnode->next = phead->next;
	newnode->prev = phead;
	phead->next->prev = newnode;
	phead->next = newnode;


}


// 双向链表头删

void ListPopFront(ListNode* phead)
{
	assert(phead);


	ListNode* cur = phead->next;

	phead->next = cur->next;

	cur->next->prev = phead;
}

// 双向链表查找

ListNode* ListFind(ListNode* phead, DataType x)
{
	assert(phead);

	ListNode* cur = phead->next;

	while (cur != phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}


	return NULL;
}

// 双向链表在pos的前面进行插入

void ListInsert(ListNode* pos, DataType x)
{

	ListNode* prev = pos->prev;

	ListNode* newnode = Creatspace(x);

	prev->next = newnode;
	newnode->prev = newnode;

	newnode->next = pos;
	pos->prev = newnode;


}

// 双向链表删除pos位置的节点

void ListErase(ListNode* pos)
{
	ListNode* prev = pos->prev;
	prev->next = pos->next;
	pos->next->prev = prev;

	free(pos);
	pos = NULL;

}
//mark up